#include<bits/stdc++.h>
using namespace std;

class Solution {
    public:
        string robotWithString(string s) {
            int n = s.size();
            vector<char> min_char(n+1);
            min_char[n - 1] = s[n - 1];
            for(int i=n-2;i>=0;i--)
            {
                min_char[i] = min(min_char[i+1], s[i]);
            }

            stack<char> st;
            string ans = "";
            for(int i=0;i<s.size();i++)
            {
                st.push(s[i]);
                while(!st.empty()&&(st.top()<=min_char[i+1]||i==n-1)){
                    ans+=st.top();
                    st.pop();
                }
            }
            return ans;
        }
    };